<template>
  <div>
    <div class="margin-container-list">
      <!--      <el-tabs v-model="selectStatus" @tab-click="selectStatusClick">
        <el-tab-pane label="已选仓库" name="1"></el-tab-pane>
        <el-tab-pane label="未选仓库" name="0"></el-tab-pane>
      </el-tabs> -->
      <!-- 操作区域 -->
      <div class="top-operate">
        <div class="pad-t-15">
          <div class="inline-flex">
            <el-select v-model="textCol" class="width-120">
              <el-option label="仓库名称" value="warehouseName"></el-option>
              <el-option label="仓库编码" value="warehouseCode"></el-option>
            </el-select>
            <el-input v-model="textValue" placeholder="请输入内容" class="width-200"></el-input>
          </div>
          <el-select v-model="searchListQuery.warehouseType" placeholder="仓库类型" clearable class="mar-l-10"
            style="width: 150px">
            <el-option v-for="(val, key) in dict.warehouseType" :key="key" :label="val" :value="key"></el-option>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button plain @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
        <!--        <div class="btn-search">
          <br>
          <el-button v-if="selectStatus == 0" @click="handleBatchSelect" type="primary">批量添加</el-button>
          <el-button v-if="selectStatus == 1" @click="handleBatchRemove" type="primary">批量移除</el-button>
        </div> -->
      </div>

      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="dataList" v-loading="listLoading" element-loading-text="加载中"
          @selection-change="handleSelectionChange">
          <!--          <el-table-column width="50px" type="selection"></el-table-column> -->
          <el-table-column label="仓库名称" min-width="220px" prop="warehouseName" />
          <el-table-column label="仓库类型" min-width="180px" prop="warehouseType">
            <template slot-scope="scope">
              {{ dict.warehouseType[scope.row.warehouseType] }}
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="140px" prop="status" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.status == 1 ? '启用' : '禁用' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="330px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <!--              <el-button v-if="selectStatus == 1" type="primary" @click="removeWarehouse(scope.row.warehouseId)">移除
              </el-button>
              <el-button v-if="selectStatus == 0" type="primary" @click="addWarehouse(scope.row.warehouseId)">添加</el-button> -->
              <el-button v-if="selectedWarehouseIds.indexOf(scope.row.warehouseId) > -1" type="success"
                @click="doAuthorize(2,scope.row)" plain>取消授权</el-button>
              <el-button v-if="selectedWarehouseIds.indexOf(scope.row.warehouseId) === -1" type="primary"
                @click="doAuthorize(1,scope.row)" plain>授权</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    pagingWarehouse,
    listWarehouseType
  } from '@/api/warehouse/warehouseInfo'
  import {
    saveGoodsGroupAuthorize,
    deleteAuthorize
  } from '@/api/goods/goodsGroup'
  export default {
    props: {
      // 商品组对象
      groupObj: {
        type: Object
      },
      showFlag: {
        type: Boolean,
        default() {
          return false
        }
      }
    },
    data() {
      return {
        // 文本model
        textCol: 'warehouseName',
        textValue: '',
        // 查询条件
        searchListQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: '',
          supplierId: '',
          warehouseSource: '',
          warehouseType: ''
        },
        total: 0,
        dataList: [],
        warehouseTypeMap: {},
        listLoading: false,
        // 选中tab
        selectStatus: '1',
        // 数据字典
        dict: {
          warehouseSource: {},
          warehouseType: {}
        },
        // 勾选仓库
        pageSelection: [],
        // 选中仓库id
        selectedWarehouseIds: []
      }
    },
    created() {
      this.groupObj.authorizeList.forEach(o => {
        if (o.authorizeType === 2 && o.warehouseId !== undefined) {
          this.selectedWarehouseIds.push(o.warehouseId)
        }
      })
      this.getWarehouseTypeList()
      this.initList()
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.groupObj.authorizeList.forEach(o => {
            if (o.authorizeType === 2 && o.warehouseId !== undefined) {
              this.selectedWarehouseIds.push(o.warehouseId)
            }
          })
          this.doResetSearch()
        } else {
          this.selectedWarehouseIds = []
        }
      }
    },
    methods: {
      getWarehouseTypeList() {
        listWarehouseType({
          enterpriseId: this.getEnterpriseId()
        }).then(response => {
          if (response.isError) return
          const warehouseTypeList = response.data
          const warehouseTypeDict = this.dict.warehouseType

          warehouseTypeList.forEach(warehouseType => {
            const key = 'third-' + warehouseType.warehouseTypeId
            warehouseTypeDict[key] = '第三方仓-' + warehouseType.warehouseTypeName
            this.warehouseTypeMap[key] = warehouseType
          })
        })
      }, // 初始化
      initList() {
        this.listLoading = true
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.supplierId = this.getSupplierId()
        this.searchListQuery.warehouseSource = this.getSupplierId() ? 2 : 1
        this.searchListQuery.selectStatus = this.selectStatus
        this.searchListQuery.selectBusinessType = 1
        this.searchListQuery.goodsGroupId = this.groupObj.goodsGroupId
        if (this.searchListQuery.warehouseType.startsWith('third-')) {
          this.searchListQuery.warehouseTypeId = this.searchListQuery.warehouseType.substr('third-'.length)
        } else {
          this.searchListQuery.warehouseTypeId = ''
        }
        pagingWarehouse(this.searchListQuery).then(response => {
          this.listLoading = false
          this.dataList = response.data.records
          // 第三方仓数据字典处理
          this.dataList.forEach(warehouse => {
            if (warehouse.warehouseType === 3) {
              warehouse.warehouseType = 'third-' + warehouse.warehouseTypeId
            }
            this.groupObj.authorizeList.forEach(o => {
              if (o.authorizeType === 2 && o.warehouseId !== undefined && o.warehouseId === warehouse
                .warehouseId) {
                warehouse.goodsGroupAuthorizeId = o.goodsGroupAuthorizeId
              }
            })
          })
          this.total = response.data.total
          const warehouseTypeDict = this.dict.warehouseType
          Object.assign(this.dict, response.data.dict)
          if (warehouseTypeDict) {
            Object.assign(this.dict.warehouseType, warehouseTypeDict)
          }
        })
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // tab切换事件
      selectStatusClick() {
        this.doResetSearch()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.searchListQuery = originData.searchListQuery
        this.doSearch()
      },
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      },
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 勾选
      handleSelectionChange(items) {
        if (items.length === 0) {
          this.pageSelection[this.searchListQuery.currentPage] = []
        } else {
          this.pageSelection[this.searchListQuery.currentPage] = items.map(item => item.warehouseId)
        }
      },
      // 批量选择仓库
      handleBatchSelect() {
        if (this.pageSelection.length === 0) {
          this.$message({
            message: '请勾选仓库',
            type: 'warning'
          })
          return
        }
        const warehouseIds = this.pageSelection[this.searchListQuery.currentPage]
        warehouseIds.forEach(warehouseId => this.selectedWarehouseIds.push(warehouseId))
      },
      // 批量移除商品
      handleBatchRemove() {
        if (this.pageSelection.length === 0) {
          this.$message({
            message: '请勾选仓库',
            type: 'warning'
          })
          return
        }
        const warehouseIds = this.pageSelection[this.searchListQuery.currentPage]
        warehouseIds.forEach(warehouseId => this.selectedWarehouseIds.splice(this.selectedWarehouseIds.findIndex(e =>
          e === warehouseId), 1))
        this.initList()
      },
      // 移除仓库
      removeWarehouse(warehouseId) {
        this.selectedWarehouseIds.splice(this.selectedGoodsIds.findIndex(e => e === warehouseId), 1)
        this.initList()
      },
      // 添加仓库
      addWarehouse(warehouseId) {
        this.selectedWarehouseIds.push(warehouseId)
        this.initList()
      },
      // 授权仓库
      doAuthorize(type, row) {
        const that = this
        const goodsGroupName = this.groupObj.goodsGroupName
        const warehouseName = row.warehouseName
        let confirmTip = ''
        // 新增授权
        if (type === 1) {
          confirmTip = '确认要授权商品组[' + goodsGroupName + ']给仓库[' + warehouseName + ']吗?'
        }
        // 删除授权
        if (type === 2) {
          confirmTip = '确认取消授权商品组[' + goodsGroupName + ']给仓库[' + warehouseName + ']吗?'
        }
        this.$confirm(confirmTip, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          that.listLoading = true
          const warehouseIdList = []
          warehouseIdList.push(row.warehouseId)
          var params = {
            enterpriseId: that.getEnterpriseId(),
            goodsGroupId: that.groupObj.goodsGroupId,
            warehouseIdList: warehouseIdList,
            authorizeType: 2 // 授权类型 1-门店 2-仓库
          }
          if (type === 1) {
            saveGoodsGroupAuthorize(params).then(response => {
              that.listLoading = false
              if (response.isError) return
              that.selectedWarehouseIds.push(row.warehouseId)
              that.msgSuccess('授权成功')
              // that.$emit('saveAuthorize')
            })
          }
          if (type === 2) {
            if (row.goodsGroupAuthorizeId === undefined) {
              this.msgError('商品组授权ID不能为空')
              return
            }
            params.goodsGroupAuthorizeIds = []
            params.goodsGroupAuthorizeIds.push(row.goodsGroupAuthorizeId)
            params.warehouseId = row.warehouseId
            deleteAuthorize(params).then(response => {
              that.listLoading = false
              if (response.isError) return
              that.selectedWarehouseIds.splice(that.selectedWarehouseIds.findIndex(item => item === row
                .warehouseId), 1)
              that.msgSuccess('取消授权成功')
              // that.$emit('saveAuthorize')
            })
          }
        }).catch(function() {

        })
      }
    }
  }
</script>

<style>
</style>
